package com.example.mymnue;

import android.os.Handler;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class ServerLet {
    private static String url="http://172.22.160.1:8084/menu/MenuServlet";
    public static final int SEND_SUCCESS=0x123;
    public static final int SEND_FAIL=0x124;
    private Handler handler;
    public ServerLet(Handler handler){
        this.handler=handler;
    }
    public void ServerLet(String title,String detail){
        final Map<String,String> map=new HashMap<String,String>();
        map.put("title",title);
        map.put("detail",detail);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (sendGet(map,url,"utf-8")){
                        handler.sendEmptyMessage(SEND_SUCCESS);
                    }else {
                        handler.sendEmptyMessage(SEND_FAIL);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private boolean sendGet(Map<String,String> map,String url,String encoding) throws Exception{
        StringBuffer sb=new StringBuffer(url);
        if (!url.equals("") & !map.isEmpty()){
            sb.append("?");
            for (Map.Entry<String, String> entry:map.entrySet()){
                sb.append(entry.getKey()+"=");
                sb.append(URLEncoder.encode(String.valueOf(entry.getValue()),encoding));
                sb.append("&");
            }
            sb.deleteCharAt(sb.length()-1);
        }
        HttpURLConnection con=(HttpURLConnection) new URL(sb.toString()).openConnection();
        con.setConnectTimeout(5000);
        con.setRequestMethod("GET");
        if (con.getResponseCode()==2000){
            return true;
        }
        return false;
    }
}
